// pages/productdetail/productdetail.js
const product = require('../../api/product.js')
const index = require('../../config/index.js')
const personal = require('../../api/personal.js')
var WxParse = require('../../wxParse/wxParse.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    product: {},
    activeNames: ['1'],
    num: 1,
    id: 0,
    arr: [],
    cartNum: 0,
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('load')
    this.setData({
      id: options.id
    })
  },
  // 根据id获取商品
  getProductById() {
    product.getProductById(this.data.id).then(res => {
      let img = res.data.data.image_detail_url.split(',')
      this.setData({
        product: res.data.data,
        imgUrls: img
      })
      if(this.data.product.content) {
        WxParse.wxParse('article', 'html', this.data.product.content, this, 0)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  // 获取用户信息
  getUserInfo(token) {
    personal.getUserInfo(token).then(res => {
      if (res.data.code == 0) {
        this.setData({
          userInfo: res.data.data
        })
        let arr = wx.getStorageSync('cart' + this.data.userInfo.id) || []
        let count = 0
        arr.forEach(value => {
          count+=value.count
        })
        this.setData({
          arr: arr,
          cartNum: count
        })
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let token = wx.getStorageSync('token')
    this.getUserInfo(token)
    this.getProductById()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  onChange(event) {
    this.setData({
      activeNames: event.detail
    });
  },
  onChangeNum(e) {
    this.setData({
      num: e.detail
    })
    if(this.data.num == this.data.product.inventory) {
      wx.showToast({
        title: '最多可购买' + this.data.product.inventory + '件',
        icon: 'none'
      })
      this.setData({
        num: this.data.product.inventory
      })
    }
  },
  // 跳转购物车
  toShopCart() {
    wx.switchTab({
      url: '../shopcart/shopcart',
      success() {
        app.setNum()
      }
    })
  },
  // 添加进购物车
  addToCart(e) {
    let that = this
    let token = wx.getStorageSync('token')
    if (!token) {
      wx.showToast({
        title: '请先登陆',
        duration: 3000,
        success() {
          wx.redirectTo({
            url: '../login/login?id=' + that.data.id,
          })
        }
      })
    } else {
      let product = this.data.product
      product.isSelect = false
      product.count = this.data.num
      let arr = wx.getStorageSync('cart' + this.data.userInfo.id) || []
      console.log(arr)
      if (arr.length > 0) {
        for (var j in arr) {
          if (arr[j].id == e.target.dataset.productid) {
            if (this.data.num > 1) {
              arr[j].count += this.data.num
            } else {
              arr[j].count += 1
            }
            if (arr[j].count > arr[j].inventory) {
              arr[j].count = arr[j].inventory
            }
            try {
              wx.setStorageSync('cart' + this.data.userInfo.id, arr)
              let cart = wx.getStorageSync('cart' + this.data.userInfo.id) || []
              let count = 0
              cart.forEach(value => {
                count += value.count
              })
              this.setData({
                cartNum: count
              })
            } catch (e) {
              console.log(e)
            }
            if(this.data.cartNum == arr[j].inventory) {
              wx.showToast({
                title: '最多可购买' + arr[j].inventory + '件',
                icon: 'none'
              })
            }else {
              wx.showToast({
                title: '加入购物车成功',
              })
            }
            return
          }
        }
        arr.push(product)
      } else {
        arr.push(product)
      }
      try {
        wx.setStorageSync('cart' + this.data.userInfo.id, arr)
        let cart = wx.getStorageSync('cart' + this.data.userInfo.id) || []
        let count = 0
        cart.forEach(value => {
          count += value.count
        })
        this.setData({
          cartNum: count
        })
        wx.showToast({
          title: '加入购物车成功'
        })
        return
      } catch (e) {
        console.log(e)
      }
    }
  },
  // 立即购买
  toBuy(e) {
    let that = this
    let token = wx.getStorageSync('token')
    if (!token) {
      wx.showToast({
        title: '请先登陆',
        success() {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    } else {
      let product = this.data.product
      let id = e.target.dataset.productid
      product.isSelect = false
      product.count = this.data.num
      let arr = wx.getStorageSync('cart' + this.data.userInfo.id) || []
      console.log(product)
      if (arr.length > 0) {
        for (var j in arr) {
          if (arr[j].id == e.target.dataset.productid) {
            if (this.data.num > 1) {
              arr[j].count += this.data.num
            } else {
              arr[j].count += 1
            }
            if (arr[j].count > arr[j].inventory) {
              arr[j].count = arr[j].inventory
            }
            try {
              wx.setStorageSync('cart' + this.data.userInfo.id, arr)
              app.setNum()
              let cart = wx.getStorageSync('cart' + this.data.userInfo.id) || []
              let count = 0
              cart.forEach(value => {
                count += value.count
              })
              this.setData({
                cartNum: count
              })
            } catch (e) {
              console.log(e)
            }
            if (this.data.cartNum == arr[j].inventory) {
              wx.showToast({
                title: '最多可购买' + arr[j].inventory + '件',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '加入购物车成功',
              })
            }
            wx.navigateTo({
              url: '../order/order?id=' + id,
            })
            return
          }
        }
        arr.push(product)
      } else {
        arr.push(product)
      }
      try {
        wx.setStorageSync('cart' + this.data.userInfo.id, arr)
        let cart = wx.getStorageSync('cart' + this.data.userInfo.id) || []
        let count = 0
        cart.forEach(value => {
          count += value.count
        })
        this.setData({
          cartNum: count
        })
        wx.navigateTo({
          url: '../order/order?id=' + id,
        })
        return
      } catch (e) {
        console.log(e)
      }
    }
  }
})